package demo.echarts.service;

import com.alibaba.fastjson.JSON;
import com.deepoove.poi.XWPFTemplate;
import com.deepoove.poi.data.Pictures;
import demo.echarts.constant.ConstantData1;
import demo.echarts.constant.ConstantData2;
import demo.echarts.constant.ConstantData3;
import demo.echarts.constant.ConstantData4;
import lombok.extern.slf4j.Slf4j;
import demo.echarts.util.Base64Util;
import demo.echarts.util.EChartsUtil;
import demo.echarts.util.FreemarkerUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.MediaTypeFactory;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.*;

/**
 * @Description ECharts 图表服务层
 * @Author Louis
 * @Date 2022/07/10 17:14
 */
@Slf4j
@Service
public class EChartsService {

    // PhontomJS 服务网址
    @Value("${phantomjs.url}")
    private String phantomjsUrl;


    /**
     * @Description 生成图表
     * title 标题
     * categories x轴数据
     * values    y轴数据
     * @Return java.io.File
     */
    public File generateEcharts(HashMap<String, Object> data,String templateFileName)  {
        // 数据参数，可以自己通过 API查询json数据
        // 模板参数 可以根据模版引擎修改，这里传入变量
        // 调用模板加载数据
        String option = FreemarkerUtil.generate(templateFileName, data);
        // 生成图片的base64编码
        String base64 = EChartsUtil.generateEChartsBase64(phantomjsUrl, option);
        // 将base64转为文件
        return Base64Util.base64ToFile(base64);
    }

    /**
     * 导出word文档
     * @param fileName
     * @return
     * @throws IOException
     */
    public ResponseEntity<Resource>  downloadWord(String fileName) throws IOException {
        // 获取echart数据
        //折线图1的源数据
        List<String> dataNull = new ArrayList<>();
        List<String> line1xAxisData = Arrays.asList(ConstantData1.xAxisData);
        List<String> line1yAxisSeriesData = Arrays.asList(ConstantData1.yAxisSeriesData);
        List<String> line1yAxisSeriesData2 = Arrays.asList(ConstantData1.yAxisSeriesData2);
        //ftl模版映射参数
        HashMap<String, Object> data1 = new HashMap<>();
        data1.put("title", "折线图1");
        data1.put("xAxisData",JSON.toJSONString(line1xAxisData));
        data1.put("yAxisSeriesData",JSON.toJSONString(line1yAxisSeriesData));
        data1.put("yAxisSeriesData1",JSON.toJSONString(dataNull));
        data1.put("yAxisSeriesData2",JSON.toJSONString(line1yAxisSeriesData2));
        data1.put("yAxisSeriesData3",JSON.toJSONString(dataNull));
        data1.put("yAxisSeriesData4",JSON.toJSONString(dataNull));
        //生成折线图1echart图表到本地目录
        File file1 = generateEcharts(data1, "EChartsLine1Option.ftl");
        System.out.println("文件:"+file1.getPath());

        //折线图2的源数据
        List<String> line2xAxisData = Arrays.asList(ConstantData1.xAxisData);
        List<String> line2yAxisSeriesData = Arrays.asList(ConstantData2.yAxisSeriesData);
        List<String> line2yAxisSeriesData1 = Arrays.asList(ConstantData2.yAxisSeriesData1);
        //ftl模版映射参数
        HashMap<String, Object> data2 = new HashMap<>();
        data2.put("title", "折线图2");
        data2.put("xAxisData",JSON.toJSONString(line2xAxisData));
        data2.put("yAxisSeriesData",JSON.toJSONString(line2yAxisSeriesData));
        data2.put("yAxisSeriesData1",JSON.toJSONString(line2yAxisSeriesData1));
        data2.put("yAxisSeriesData2",JSON.toJSONString(dataNull));
        data2.put("yAxisSeriesData3",JSON.toJSONString(dataNull));
        //生成折线图1echart图表到本地目录
        File file2 = generateEcharts(data2, "EChartsLine2Option.ftl");
        System.out.println("文件:"+file2.getPath());

        //折线图3的源数据
        List<String> line3xAxisData = Arrays.asList(ConstantData3.xAxisData);
        //ftl模版映射参数
        HashMap<String, Object> data3 = new HashMap<>();
        data3.put("title", "折线图3");
        data3.put("xAxisData",JSON.toJSONString(line3xAxisData));
        data3.put("yAxisSeriesData",JSON.toJSONString(dataNull));
        data3.put("yAxisSeriesData1",JSON.toJSONString(dataNull));
        data3.put("yAxisSeriesData2",JSON.toJSONString(dataNull));
        //生成折线图1echart图表到本地目录
        File file3 = generateEcharts(data3, "EChartsLine3Option.ftl");
        System.out.println("文件:"+file2.getPath());

        //环图的源数据
        List<HashMap<String,Object>>  piexAxisData = ConstantData4.dataPie;
        //ftl模版映射参数
        HashMap<String, Object> data4 = new HashMap<>();
        data4.put("title", "环图");
        data4.put("dataPie",JSON.toJSONString(piexAxisData));

        //生成折线图1echart图表到本地目录
        File file4 = generateEcharts(data4, "EChartsPieOption.ftl");
        System.out.println("文件:"+file4.getPath());
       //word模版映射参数
        Map data = new HashMap<String, Object>();
        //word模版设置图片
        data.put("image1", Pictures.ofLocal(file1.getPath()).size(630, 270).center().create());
        data.put("image2", Pictures.ofLocal(file2.getPath()).size(630, 270).center().create());
        data.put("image3", Pictures.ofLocal(file3.getPath()).size(630, 270).center().create());
        data.put("image4", Pictures.ofLocal(file4.getPath()).size(630, 270).center().create());

        //word模版设置值
        data.put("number1", 30.56);
        data.put("value1", "测试模版数据1");
        //获取word模版
        ClassPathResource classPathResource = new ClassPathResource("templates/word/模版.docx");
        System.out.println("word路径:"+classPathResource.getPath());
        InputStream inputStream =classPathResource.getInputStream();
        //编译word模版
        XWPFTemplate template = XWPFTemplate.compile(inputStream).render(data);
       // template(ParagraphAlignment.CENTER);
        inputStream.close();
        //生成新word到本地
        template.writeAndClose(new FileOutputStream(file1.getParent()+"/"+fileName));
        template.close();
        Resource resource = new FileSystemResource(file1.getParent()+"/"+fileName);
        //删除临时生成的echart图片
        file1.delete();
        file2.delete();
        file3.delete();
        file4.delete();
        if (resource == null || !resource.exists()) {
            return ResponseEntity.notFound().build();
        } else {
            //接口返回
            fileName  = URLEncoder.encode(fileName, "UTF-8");
            HttpHeaders headers = new HttpHeaders();
            MediaType mediaType = MediaTypeFactory.getMediaType(fileName).orElse(MediaType.APPLICATION_OCTET_STREAM);
            headers.setContentDispositionFormData("attachment", fileName);
            headers.setContentLength((int) resource.contentLength());
            headers.setContentType(mediaType);

            return ResponseEntity.ok()
                    .headers(headers)
                    .body(resource);
        }
    }

}
